package com.nh.glory.ware.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nh.glory.core.R;
import com.nh.glory.core.util.JsonMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class StatelessAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper mapper = JsonMapper.INSTANCE.getMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        if (exception instanceof BadCredentialsException) {
            mapper.writeValue(response.getWriter(), R.fail(401, exception.getMessage()));
        } else if (exception instanceof AuthenticationServiceException) {
            mapper.writeValue(response.getWriter(), R.fail(401, exception.getMessage()));
        }

        mapper.writeValue(response.getWriter(), R.fail(401, "Authentication failed"));
    }

}
